package server;

import java.util.ArrayList;
import java.util.List;

import util.CardParser;
/**
 * This class manipulates all the card messages, being helped by the CardParser.
 *
 */
public class Gambler {
	private CardParser myCardParser = new CardParser();
	
	private static Gambler singleton= null;
	// Singleton

	private ArrayList<Card> deck; 
	//Needs to be the full deck, singleton-instances
	
	public static Gambler newGambler() {
		if (singleton!=null) {return singleton;}
		return new Gambler();
	}
	/**
	 * Private Constructor. 
	 * Required for singleton pattern.
	 * 
	 * Creates a new Gambler with a sorted deck of card.
	 */
	private Gambler() {
		ArrayList<Card> deck = fillCards();
		this.deck = deck;
	}
	
	private ArrayList<Card> fillCards() {
		ArrayList<Card> deck = new ArrayList<Card>();
		for (CardSuits suit : CardSuits.values()) {
			for (int i = 1; i<=13;i++) { deck.add(new Card(suit, i)); }
		}
		return deck;
	}
	
	
	public void reFillCards() {
		this.deck =  fillCards();
	}
	/**
	 * Randomize the cards on the deck.
	 */
	public void shuffle() {
		ArrayList<Card> newdeck = new ArrayList<Card>();
		int size = this.deck.size();
		for (int i=0;i<size;i++) {
			int cardPos = (int) (Math.random()*this.deck.size());
			newdeck.add(this.deck.remove(cardPos));
		}
		this.deck=newdeck;
	}
	
	public CardParser getCardParser(){
		return this.myCardParser;
	}
	
	
	/**
	 * Get the first Card of the deck
	 * @return
	 */
	public Card getCard() {
		Card c = this.deck.remove(0);
		return c;
	}

	/**
	 * Get a specified number of cards of the deck
	 * @param number how many cards will be retrieved.
	 * @return
	 */
	public List<Card> getCards(int number) {
		List<Card> cards = new ArrayList<Card>(); 
		for (int i=0;i<number;i++) {
			cards.add(this.getCard());
		}
		return cards;
	}
	
	
	/**
	 * 
	 */
	
	
	/**
	 * A String representation of the Object.
	 */
	public String toString() {
		String result="[";
		for (Card card : this.deck) {
			result = result.concat(" "+card.suit.toString());
			result = result.concat("."+card.number );
		}
		return result + "]";
	}
	
	/**
	 * Main class.... just for testing!
	 * @param args
	 */
	public static void main(String[] args) {
		Gambler g = Gambler.newGambler();
		System.out.println(g);
		String test = g.getCardParser().inputParseCard(g.getCard());
		System.out.println(test);
		g.shuffle();
		ArrayList<Card> lc = g.deck;
		String test2 = g.getCardParser().inputParseCards(lc);
		System.out.println(g);
		System.out.println(test2);
		//-----------------------//
		Card testCard = g.getCardParser().outputParseCard(test);
		System.out.println(testCard.getNumber());
		System.out.println(testCard.getSuit());
		System.out.println(test2.length());
		List<Card> codedCards = g.getCardParser().outputParseCards(test2);
		System.out.println(codedCards);

	}
}
